<template>
  <el-container>
    <el-header style="height:auto;">
      <div style="padding: 10px;">
      <el-page-header @back="goBack">
        <template slot="title">
          返回机构列表
        </template>
        <template slot="content">
          当前机构：{{ `${orgItem.orgName}[${orgItem.orgId}]` }}
        </template>
      </el-page-header>
      </div>
    </el-header>
    <el-main style="padding-top: 0;">
      <el-container>
        <el-aside style="width:260px; padding: 10px">
          <el-tree ref="deptTree"
            :data="treeData"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false" @node-click="nodeClick">
            <span slot-scope="{ data }" >
              <span>{{ data.data.deptName }}</span>
            </span>
          </el-tree>
        </el-aside>
        <el-main style="padding: 0;">
          <el-container>
            <el-header style="height:auto">
              <template v-if="currentItem.id">
                <h3 style="margin: 10px; padding: 0px;">当前部门：{{ currentItem.data.deptPath }}</h3>
                <el-button icon="el-icon-edit" round @click="edit">编辑</el-button>
                <el-button type="primary" icon="el-icon-plus" round @click="add">添加子部门</el-button>
                <el-button type="primary" icon="el-icon-delete" round @click="remove">删除当前部门</el-button>
              </template>
            </el-header>
            <el-main>
              <el-table height="100%" :data="dataTable.result" border style="width: 100%" highlight-current-row>
                <el-table-column prop="displayName" label="姓名" width="150"></el-table-column>
                <el-table-column prop="loginName" label="登录名" width="150"></el-table-column>
                <el-table-column prop="cellphone" label="手机号" width="200"></el-table-column>
                <el-table-column prop="secEmail" label="邮箱" min-width="200" show-overflow-tooltip></el-table-column>
                <!-- <el-table-column prop="userStatus" label="用户状态" width="100">
                  <template slot-scope="scope">
                    {{ userStatus.singleOrDefault(t=>t.value == scope.row.userStatus).label }}
                  </template>
                </el-table-column> -->
                <el-table-column header-align="center" align="center" width="60" fixed="right">
                  <template slot="header">
                    <el-button type="text" icon="el-icon-plus" @click="showExclusionUsers = true" title="新增" ></el-button>
                  </template>
                  <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-delete" @click="removeUser(scope.row)" title="删除"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-main>
            <el-footer>
              <el-pagination v-on:current-change="getUsers" :current-page.sync="queryObject.pageIndex" :page-size="queryObject.pageSize" layout="total, prev, pager, next" :total="dataTable.rowCount" ></el-pagination>
            </el-footer>
          </el-container>
        </el-main>
      </el-container>

      <el-drawer :title="formTitle" :visible.sync="showEdit" @close="closeDialog" direction="rtl">
        <template slot="title">
          <div>
            <el-button @click="showEdit = false">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </div>
        </template>
        <el-container>
          <el-main>
            <el-form :model="editItem" label-width="100px">
              <el-form-item label="部门名称">
                <el-input v-model="editItem.deptName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="排序值">
                <el-input v-model="editItem.ordinal" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="部门简介">
                <el-input v-model="editItem.description" type="textarea" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
          </el-main>
        </el-container>

      </el-drawer>


      <el-dialog title="请选择用户" :visible.sync="showExclusionUsers" @opened="openUsers">
        <ExclusionUsers ref="exclusionUsers" :orgId="orgId" :deptId="currentItem.id"></ExclusionUsers>

        <div slot="footer" class="dialog-footer">
          <el-button @click="showExclusionUsers = false">取 消</el-button>
          <el-button type="primary" @click="addUsers">确 定</el-button>
        </div>
      </el-dialog>

    </el-main>
  </el-container>
</template>
<script>
import ExclusionUsers from './components/ExclusionUsers.vue';
export default {
  components:{
    ExclusionUsers
  },
  data() {
    return {
      createNew: true,
      showEdit: false,
      orgId: null,
      orgItem: {
        orgId: null,
        orgName: null
      },
      treeData:[],
      currentItem: {
        id: null,
        data: {

        },
        children:[]
      },
      editItem: {
        deptId: null,
        orgId: null,
        deptName: null,
        parentDeptId: null,
        director: null,
        ordinal: 0,
        description: null
      },
      queryObject: {
        pageIndex: 1,
        pageSize: 20,
        sortFields: {
          "UserID": true,
        },
        parameters: {
          keyword: null,
          userStatus: null,
        },
      },
      dataTable: {
        result: [],
        pageIndex: 1,
        pageSize: 20,
        pageCount: 0,
        rowCount: 0,
      },
      showExclusionUsers: false,

    }
  },
  computed: {
    formTitle(){
      return this.createNew ? "新建子部门":"编辑当前部门";
    }
  },
  created() {
    this.orgId = this.$route.params.id;
    this.$service.org.item({params:{id:this.orgId}}).then(r => {
      if (r.success) {
        this.orgItem = r.data;
        this.getDepts();
      }
    });
  },
  methods: {
    getDepts(){
      this.$service.org.depts({params:{orgId: this.orgId}}).then(r => {
        if (r.success){
          let root = r.data;
          this.treeData = [root];
          this.$refs.deptTree.setCurrentKey(root.id);
        }
      });
    },
    getUsers(){
      this.$service.org.getUsers({params:{orgId: this.orgId, deptId: this.currentItem.id}, data: this.queryObject}).then(r => {
        if (r.success){
          this.dataTable = r.data;
        }
      });
    },
    nodeClick(data){
      this.currentItem = data;
      this.getUsers();
    },
    closeDialog(){
    },
    resetForm(){
      for(var name in this.editItem)
        this.editItem[name] = null;
    },
    add(){
      this.resetForm();
      let data = this.currentItem.data;
      this.editItem.orgId = data.orgId;
      this.editItem.parentDeptId = data.deptId;

      this.showEdit = true;
      this.createNew = true;
    },
    edit(){
      this.resetForm();
      for(var name in this.editItem)
        this.editItem[name] = this.currentItem.data[name];
      this.showEdit = true;
      this.createNew = false;
    },
    save(){
      let postdata = {data: this.editItem};
      let task = this.createNew ? this.$service.org.createDept(postdata) : this.$service.org.updateDept(postdata);
      task.then((response) => {
        if (response.success){
          let vo = response.data;
          if (this.createNew){
            this.currentItem.children = this.currentItem.children || [];
            this.currentItem.children.push({
              id: vo.deptId,
              data: vo,
              children: []
            });
          }
          else{
            for(var name in this.currentItem.data)
              this.currentItem.data[name] = vo[name];

          }
          alert("保存成功","消息","success", ()=>{this.showEdit = false; this.createNew = true;});

        }
      });
    },
    remove(){
      let data = this.currentItem.data;
      confirm('确认要删除['+data.deptName+']吗？请谨慎操作！', '警告', 'warning', ()=>{

        this.$service.org.deleteDept({data:data.deptPath}).then((response) => {
          if (response.success) {
            this.getDepts();
          }
          else{
            let msg = response.message || "操作失败";
            alert(msg,"消息","error");
          }
        });
      });
    },
    openUsers(){
      this.$refs.exclusionUsers.query();
    },
    addUsers(){

      let data = this.currentItem.data;
      let items = this.$refs.exclusionUsers.getSelection();
      this.$service.org.addUsers({
        data: {deptPath: data.deptPath, users:items}
      }).then(r =>{
        if(r.success)
          this.getUsers();
      });

      this.showExclusionUsers = false;
    },
    removeUser(row){
      confirm('确认从部门中删除['+row.displayName+']吗？请谨慎操作！', '警告', 'warning', ()=>{

        let data = this.currentItem.data;
        this.$service.org.removeUsers({data: {deptPath: data.deptPath,  users: [row.userId]}}).then((response) => {
          if (response.success) {
            this.getUsers();
          }
          else {
            let msg = response.message || "操作失败";
            alert(msg,"消息","error");
          }
        });
      });
    },
    goBack(){

      this.$router.push({name:'orgRoot'})
    }
  }
}
</script>
